<template>
  <el-dialog
    title="修改字典项"
    :visible.sync="dialogVisible"
    :before-close="cancel"
    :close-on-click-modal="false"
    class="vc-dialog-form"
    width="480px">
    <el-form ref="editForm" :model="editForm" :rules="rules" label-width="100px" size="small">
      <el-form-item label="字典名称" prop="dicName">
        <el-input v-model="editForm.dicName" disabled></el-input>
      </el-form-item>

      <el-form-item label="字典项名称" prop="name">
        <el-input v-model="editForm.name" maxlength="20" placeholder="请输入" clearable @clear="$refs.addForm.validateField('name')"></el-input>
      </el-form-item>

      <el-form-item label="字典项编码" prop="code">
        <el-input v-model="editForm.code" disabled></el-input>
      </el-form-item>

      <el-form-item label="显示排序" prop="showOrder">
        <el-input v-model="editForm.showOrder" maxlength="5" placeholder="请输入" clearable @input="filterShowOrder"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button type="primary" size="small" :disabled="disabled" @click="save">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { validateInput } from '@/utils/validator';

export default {
  name: 'editItem',
  props: ['dialogVisible', 'entity', 'dicName'],
  data() {
    return {
      editForm: {
        dicId: '',
        dicName: '',
        name: '',
        code: '',
        showOrder: null
      },
      rules: {
        name: [
          { required: true, message: '请输入字典项名称', trigger: 'blur' },
          { validator: validateInput, trigger: 'blur' }
        ]
      },
      disabled: false
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) return;
      this.disabled = false;
    },
    entity: {
      handler(val) {
        this.editForm = Object.assign({}, this.entity, { dicName: this.dicName });
        this.$nextTick(() => { this.$refs.editForm && this.$refs.editForm.clearValidate(); });
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     * 保存
     */
    save() {
      if (this.disabled) {
        return;
      }
      this.$refs.editForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.disabled = true;
        this.$api.updateDicItem({
          data: this.editForm
        }).then(res => {
          if (!res.success) {
            this.disabled = false;
            return;
          }
          this.$emit('close', res.data || {});
          this.$notifyBox('保存成功', 'success');
        }).catch(() => {
          this.disabled = false;
        });
      });
    },
    /**
     * 取消
     */
    cancel() {
      this.$emit('close', false);
    },
    /**
     * 过滤'显示排序'输入值
     */
    filterShowOrder(val) {
      this.editForm.showOrder = this.GLOBAL.filter.filterNaN(val);
    }
  }
}
</script>
